package com.trace.demo.repository;

import com.trace.demo.entity.DistributionRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 分销记录数据访问接口
 */
@Repository
public interface DistributionRecordRepository extends JpaRepository<DistributionRecord, Long> {

    /**
     * 根据分销商ID查找分销记录
     */
    @Query("SELECT d FROM DistributionRecord d WHERE d.distributor.id = :distributorId")
    List<DistributionRecord> findByDistributorId(@Param("distributorId") Long distributorId);

    /**
     * 根据产品ID查找分销记录
     */
    @Query("SELECT d FROM DistributionRecord d WHERE d.product.id = :productId")
    List<DistributionRecord> findByProductId(@Param("productId") Long productId);

    /**
     * 统计特定分销商的分销记录数
     */
    @Query("SELECT COUNT(d) FROM DistributionRecord d WHERE d.distributor.id = :distributorId")
    long countByDistributorId(@Param("distributorId") Long distributorId);

    /**
     * 统计特定产品的分销记录数
     */
    @Query("SELECT COUNT(d) FROM DistributionRecord d WHERE d.product.id = :productId")
    long countByProductId(@Param("productId") Long productId);

    /**
     * 根据分销商ID和创建时间查询分销记录
     */
    @Query("SELECT d FROM DistributionRecord d WHERE d.distributor.id = :distributorId AND d.createdAt > :date")
    List<DistributionRecord> findByDistributorIdAndCreatedAtAfter(@Param("distributorId") Long distributorId, @Param("date") LocalDateTime date);

    /**
     * 根据产品ID和创建时间查询分销记录
     */
    @Query("SELECT d FROM DistributionRecord d WHERE d.product.id = :productId AND d.createdAt > :date")
    List<DistributionRecord> findByProductIdAndCreatedAtAfter(@Param("productId") Long productId, @Param("date") LocalDateTime date);

    /**
     * 查询在指定时间之后创建的分销记录
     */
    @Query("SELECT d FROM DistributionRecord d WHERE d.createdAt > :date")
    List<DistributionRecord> findByCreatedAtAfter(@Param("date") LocalDateTime date);
}
